<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'csw:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $app = app('wechat.official_account');
        $list = $app->material->list('image', 0, 10);
        foreach($list['item'] as $item) {
            echo $item['media_id']. "\t". $item['name'] ."\n";
        }
    }

    protected function testSendMail()
    {
        $transport = (new \Swift_SmtpTransport('smtp.exmail.qq.com', 465, 'ssl'))
            ->setUsername('chensw@gzads.com')
            ->setPassword('Tureture#123')
        ;

        $mailer = new \Swift_Mailer($transport);
        $message = (new \Swift_Message('公众号统计信息'))
            ->setFrom(['chensw@gzads.com' => 'chenshengwen'])
            ->setTo(['chensw@gzads.com'])
            ->setBody('Here is the message itself')
        ;
        $result = $mailer->send($message);
    }

    protected function setOAMenu()
    {
        $menuQuery = new \App\Models\Menu();
        $buttons = [];
        $nodes = $menuQuery::where("parent_id", 0)->get();
        foreach($nodes as $node) {
            $this->info($node['name']);
            $button = $this->formatNote($node);
            $children = [];
            $childrenNodes = $menuQuery::where("parent_id", $node->id)->get();
            if($childrenNodes) {
                foreach ($childrenNodes as $childrenNode) {
                    $children[] = $this->formatNote($childrenNode);
                }
                $button['sub_button'] = $children;
                unset($button['type']);
                unset($button['key']);
                unset($button['url']);
            }
            $buttons[] = $button;
        }
        $app = app('wechat.official_account');
        $app->menu->create($buttons);
        $this->info(json_encode($buttons));
    }

    protected function formatNote($node)
    {
        $button = [];
        $button['type'] = $node->type;
        $button['name'] = $node->name;
        if($node->type == 'click') {
            $button['key'] = $node->key;
        }
        if($node->type == 'view') {
            $button['url'] = $node->url;
        }
        return $button;
    }
}
